package com.wlyuan.open.scanner.application.listener.table;

import com.wlyuan.open.scanner.application.factory.TableNameHandlerFactory;
import com.wlyuan.open.scanner.service.ScannerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TableListener {
    private final ScannerService scannerService;

    /**
     * 增量监听计划
     *
     * @param sourceId   业务来源id
     * @param tableName  表名
     * @param data       数据
     * @param beforeData 之前数据
     */
    public void schema(Long sourceId, String tableName, String data, String beforeData) {
        var list = getScannerName(tableName, data, beforeData);
        if (CollectionUtils.isEmpty(list)) {
            logger.error("没有找到对应表名{}的数据变化业务处理实现", tableName);
            return;
        }
        list.forEach(name -> this.incr(sourceId, name));
    }

    private void incr(Long sourceId, String name) {
        scannerService.increment(String.valueOf(sourceId), name);
    }

    private List<String> getScannerName(String tableName, String data, String beforeData) {
        return Optional.ofNullable(TableNameHandlerFactory.getTableHandler(tableName)).map(h -> h.handler(tableName, data, beforeData)).orElse(null);
    }

}
